
cc.Class({
    extends: cc.Component,

    properties: {
        txtGrade: cc.Label,
        txtTime: cc.Label,
        btnStart: cc.Button,
        nodeBeat: cc.Node,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this._lefttime = 10;
        this._grade = 0;
        this.nodeBeat.active = false;
    },

    start () {
        this.nodeBeat.on(cc.Node.EventType.TOUCH_START, event => {
            this.nodeBeat.scale = 1.1;
        });

        this.nodeBeat.on(cc.Node.EventType.TOUCH_END, event => {
            this.nodeBeat.scale = 1.0;
            this._grade++;
            this.txtGrade.string = `面长${this._grade}米`;
        });
    },

    // update (dt) {},

    updateGrade(){
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            let max = cc.sys.localStorage.getItem('max_grade');
            if(max != null && max < this._grade){
                cc.sys.localStorage.setItem('max_grade', this._grade);
                let KVDataList = [{key:'grade', value: this._grade.toString()}];

                wx.setUserCloudStorage({
                    KVDataList: KVDataList,
                    success: res => {
                        console.log('success', res);
                    },
                    
                    faile: res => {
                        console.log('faile', res);
                    }
                });
            }            
        }        
    },

    startGame(){
        this.btnStart.node.active = false;
        this.nodeBeat.active = true;

        this._lefttime = 10;
        this._grade = 0;
        this.txtGrade.string = `面长${this._grade}米`;;
        this.txtTime.string = `剩余：${this._lefttime}秒`;
        this.schedule(this.onTimerCallback, 1);
    },

    onTimerCallback(){
        this._lefttime--;
        this.txtTime.string = this._lefttime;
        this.txtTime.string = `剩余：${this._lefttime}秒`;

        if(this._lefttime <= 0){
            this.unschedule(this.onTimerCallback);
            this.btnStart.node.active = true;
            this.nodeBeat.active = false;
            this.updateGrade();
        }
    },

    onClick(event, data){
        switch(data){
            case 'start':{
                this.startGame();
                break;
            }
            case 'back':{
                cc.director.loadScene('main');
                break;
            }
        }
    },
});
